<template>
    <div>
        <h-section title="需求情况" collapse>
            <div style="margin-top: 16px; font-size: 14px">需求数据统计</div>
            <custom-table
                ref="ruleTableRef"
                class="margin-t-16"
                size="small"
                :pagination="false"
                :columns="detailColumns.columnsF"
                :data-source="detail.requireInfos || []"
            >
                <template #type="{ text }">
                    {{ text === '1' ? '业务需求' : '产品需求' }}
                </template>
                <template #addCount="{ record }">
                    <flexbox>
                        <a @click="jumpTo(record.type, record.addIds)" v-if="record.addCount">{{ record.addCount }}</a>
                        <span v-else-if="record.addCount === 0">{{ record.addCount }}</span>
                    </flexbox>
                </template>
                <template #yonyGrowth="{ record }">
                    <flexbox v-if="record.addCount || record.addCount == 0">
                        <flexbox :class="record.addCount - record.lastAddCount > 0 ? 'error-color' : 'success-color'" v-if="record.lastAddCount">
                            {{ record.lastAddCount ? ((record.addCount - record.lastAddCount) / record.lastAddCount).toFixed(2) : '' }}
                            <ArrowUpOutlined v-if="record.addCount - record.lastAddCount > 0" />
                            <ArrowDownOutlined v-else />
                        </flexbox>
                    </flexbox>
                </template>
                <template #processCount="{ record }">
                    <flexbox>
                        <a @click="jumpTo(record.type, record.processIds, '2')" v-if="record.processCount">{{ record.processCount }}</a>
                        <span v-else>{{ record.processCount || 0 }}</span>
                    </flexbox>
                </template>
                <template #onlineCount="{ record }">
                    <a @click="jumpTo(record.type, record.onlineIds, '3')" v-if="record.onlineCount">{{ record.onlineCount }}</a>
                    <span v-else>{{ record.onlineCount || 0 }}</span>
                </template>
                <template #suspendCount="{ record }">
                    <a @click="jumpTo(record.type, record.suspendIds, '6')" v-if="record.suspendCount">{{ record.suspendCount }}</a>
                    <span v-else>{{ record.suspendCount || 0 }}</span>
                </template>
            </custom-table>
        </h-section>

        <h-section collapse>
            <template #title>
                <flexbox>
                    <span>{{ `${detail.reportPeriod}已发布版本` }}</span>
                    <a-tooltip title="按照预发布版本的【上线日期】在时间段内统计">
                        <QuestionCircleOutlined class="margin-l-8" />
                    </a-tooltip>
                </flexbox>
            </template>
            <release-version-table
                ref="releaseVersionTableRef"
                :list="detail.releaseVersion"
                :detail="detail"
                :hasAuth="hasAuth"
                :isNoData="isNoData"
                @success="handleSuccess"
            >
            </release-version-table>
        </h-section>

        <h-section collapse>
            <template #title>
                <flexbox>
                    <span>进行中版本</span>
                    <a-tooltip title="按照预发布版本的【创建时间】在时间段内统计">
                        <QuestionCircleOutlined class="margin-l-8" />
                    </a-tooltip>
                </flexbox>
            </template>
            <process-version-table
                ref="processVersionTableRef"
                :list="detail.processVersion"
                :detail="detail"
                :hasAuth="hasAuth"
                :isNoData="isNoData"
                @success="handleSuccess"
            >
            </process-version-table>
        </h-section>
        <AddJiraRequireModal ref="AddJiraRequireModalRef" @success="handleSuccess" />
        <AddJiraVersionModal ref="AddJiraVersionModalRef" @success="handleSuccess" />
    </div>
</template>

<script lang="ts">
import api from '@/api';
import store from '@/store';
import { useRouter } from 'vue-router';
import { useMessage } from '@/hooks/common/useMessage';
import { ReleaseVersionTable, ProcessVersionTable } from './components/index';
import {
    QuestionCircleOutlined,
    ClockCircleOutlined,
    CloseCircleOutlined,
    CheckCircleOutlined,
    ExclamationCircleOutlined,
    ArrowUpOutlined,
    ArrowDownOutlined
} from '@ant-design/icons-vue';
import { useRouterApi } from '@/hooks/common/useRouterApi';
import { detailColumns } from '@/views/energyManage/analysisReport/config/detailColumns';
import { CustomTable } from '@/components';
import { defineComponent, ref, unref, reactive, toRefs, computed } from 'vue';
import AddJiraRequireModal from './components/AddJiraRequireModal.vue';
import AddJiraVersionModal from './components/AddJiraVersionModal.vue';
import { message } from 'ant-design-vue/es';
export default defineComponent({
    components: {
        QuestionCircleOutlined,
        ClockCircleOutlined,
        CloseCircleOutlined,
        CheckCircleOutlined,
        ExclamationCircleOutlined,
        ReleaseVersionTable,
        ProcessVersionTable,
        CustomTable,
        AddJiraRequireModal,
        AddJiraVersionModal,
        ArrowUpOutlined,
        ArrowDownOutlined
    },
    props: {
        hasAuth: {
            type: Boolean,
            default: false
        },
        isNoData: {
            type: Boolean,
            default: false
        },
        detail: {
            type: Object,
            default: () => ({})
        }
    },
    setup(props, { emit }) {
        const router = useRouter();
        const { createJiraLogin, createConfirm } = useMessage();
        const releaseVersionTableRef = ref<any>();
        const processVersionTableRef = ref<any>();
        const unOnlineVersionTableRef = ref<any>();
        const ZhuanbanModalRef = ref<any>();
        const AddJiraRequireModalRef = ref<any>();
        const AddJiraVersionModalRef = ref<any>();
        const { handleBack, route } = useRouterApi({
            backQuery: {
                path: '/energyManage/analysisReport'
            }
        });
        const state = reactive<any>({
            isLoginJira: false,
            errorVersion: []
        });
        const disabled = computed(() => {
            return +props.detail.stage > 2 || !props.hasAuth || props.isNoData;
        });
        // 移除版本号规则错误版本
        const handleDeleteErrorVersion = async (id: any) => {
            const query = {
                id
            };
            const { success, errorMsg } = await api.requireReportModel.deleteRRInfoJiraById(query);
            if (success) {
                handleSuccess();
            } else {
                message.error(errorMsg);
            }
        };
        const validate = async () => {
            state.errorVersion = [];
            // 检测所有数据版本号
            const validateAllList = () => {
                const { releaseVersion, processVersion, processOverDueVersion } = props.detail;
                const list = [...releaseVersion, ...processVersion, ...processOverDueVersion];
                return new Promise((resolve) => {
                    let res = true;
                    list.forEach((item) => {
                        if (Reflect.has(item, 'versionNumber') && item['versionNumber']) {
                            const reg1 = /^[a-zA-Z0-9-]+\.[a-zA-Z0-9]+\.[a-zA-Z0-9]+$/gi;
                            const reg2 = /^[a-zA-Z0-9-]+\.[a-zA-Z0-9]+\.[a-zA-Z0-9]+\.[a-zA-Z0-9]+$/gi;
                            if (reg1.test(item['versionNumber']) || reg2.test(item['versionNumber'])) {
                            } else {
                                res = false;
                                state.errorVersion.push(item);
                            }
                        }
                    });
                    if (!res) {
                        const projectKey = props.detail.jiraSyncTmplDTO?.projectKey;
                        const errorVersionNumbers = state.errorVersion.map((item: { [x: string]: any }) => item['versionNumber']).join(',');
                        createConfirm({
                            title: '提示',
                            iconType: 'warning',
                            content: `${errorVersionNumbers}版本号不正确，请按照X.X.X的命名格式命名版本号，其中每一位允许数字英文或“-”符号`,
                            okText: '去JIRA修改',
                            onOk: async () => {
                                // 移除掉不规范的版本
                                const errorVersionIds = state.errorVersion.map((item: { [x: string]: any }) => item['id']).join(',');
                                handleDeleteErrorVersion(errorVersionIds);
                                window.open(
                                    `http://jira.showcai.com.cn:8080/projects/${projectKey}?selectedItem=com.atlassian.jira.jira-projects-plugin:release-page`,
                                    '_blank'
                                );
                            }
                        });
                    }
                    resolve(res);
                });
            };
            // validateProList(),
            return await Promise.all([validateAllList(), unref(releaseVersionTableRef).validate(), unref(processVersionTableRef).validate()]);
        };
        const getList = () => {
            let { businessInfos, productInfos, requireInfos, releaseVersion, processVersion, processOverDueVersion } = props.detail;
            requireInfos = requireInfos.map((item: { processCount: any; onlineCount: any; suspendCount: any; addCount: any }) => ({
                ...item,
                processCount: item.processCount || 0,
                onlineCount: item.onlineCount || 0,
                suspendCount: item.suspendCount || 0,
                addCount: item.addCount || 0
            }));
            businessInfos = businessInfos || [];
            productInfos = productInfos || [];
            requireInfos = requireInfos || [];
            releaseVersion = releaseVersion || [];
            processVersion = processVersion || [];
            processOverDueVersion = processOverDueVersion || [];
            return [...businessInfos, ...productInfos, ...requireInfos, ...releaseVersion, ...processVersion, ...processOverDueVersion];
        };
        const handleDelete = async (id: any) => {
            const query = {
                id
            };
            const { success, errorMsg } = await api.requireReportModel.deleteRRInfoJiraById(query);
            if (success) {
                message.success('移除成功');
                emit('success');
            } else {
                message.error(errorMsg);
            }
        };
        const handleAddIssue = async (type: any) => {
            if (state.isLoginJira) {
                unref(AddJiraRequireModalRef).open(props.detail, type);
            } else {
                createJiraLogin({
                    systemId: props.detail.systemId,
                    onOk() {
                        state.isLoginJira = true;
                        unref(AddJiraRequireModalRef).open(props.detail, type);
                    }
                });
            }
        };
        const handleAddVersion = async (type: any) => {
            if (state.isLoginJira) {
                unref(AddJiraVersionModalRef).open(props.detail, type);
            } else {
                createJiraLogin({
                    systemId: props.detail.systemId,
                    onOk() {
                        unref(AddJiraVersionModalRef).open(props.detail, type);
                    }
                });
            }
        };
        const handleSuccess = () => {
            emit('success');
        };
        const jumpTo = (type: string, ids: any, status = '') => {
            const query: any = {
                ids,
                type,
                systemName: props.detail.systemName
            };
            const path = type === '1' ? '/energyManage/analysisReport/taskDetailList' : '/energyManage/analysisReport/proDetailList';
            if (status) {
                query.status = status;
            }
            router.push({
                path,
                query
            });
        };
        const checkIsLoginJira = async () => {
            const { errorCode } = await api.jiraModel.getIssuesByConditions({
                empId: store.getters.userInfo.employeeDTO.empId,
                systemId: props.detail.systemId
            });
            if (errorCode === '003') {
                state.isLoginJira = false;
            } else {
                state.isLoginJira = true;
            }
        };
        const init = () => {
            checkIsLoginJira();
        };
        init();
        return {
            ...toRefs(state),
            handleBack,
            releaseVersionTableRef,
            processVersionTableRef,
            unOnlineVersionTableRef,
            ZhuanbanModalRef,
            validate,
            getList,
            handleAddIssue,
            handleAddVersion,
            detailColumns,
            AddJiraRequireModalRef,
            AddJiraVersionModalRef,
            handleSuccess,
            handleDelete,
            disabled,
            jumpTo
        };
    }
});
</script>
<style scoped lang="less">
.page-wrap {
    height: 100%;
    position: relative;
    .page-cont {
        background: #fff;
        .btn-group {
            margin: 24px 0;
            button + button {
                margin-left: 8px;
            }
        }
        .tip-cont {
            color: #d46b08;
            background: #fff7e6;
            border-color: #ffd591;
            padding: 6px 12px;
            font-size: 14px;
        }
    }
}
// 去掉表头颜色
::v-deep(.ant-table-thead) > tr > th {
    background: #eaf5fe !important;
    font-weight: 400;
    color: @primary-color;
}
::v-deep(.ant-divider) {
    border-top: 2px solid #eaf5fe;
}
::v-deep(.ant-table-row-hover) > td {
    background: none !important;
}
</style>